package com.godyao.mall.user.boot.repository;

import com.godyao.mall.user.common.model.SysRole;
import com.godyao.mall.user.common.model.vo.SysRolePermissionVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @author godyao
 * @date 2022/4/2
 */
public interface SysRoleRepository extends JpaRepository<SysRole, Long> {

    @Query(nativeQuery = true, value = "SELECT " +
            "id," +
            "NAME," +
            "CODE," +
            "CREATE_TIME," +
            "UPDATE_TIME," +
            "STATUS " +
            "FROM " +
            "sys_role sr " +
            "WHERE " +
            "sr.STATUS = 1 " +
            "AND EXISTS (" +
            "SELECT " +
            "sur.role_id " +
            "FROM " +
            "sys_user_role sur " +
            "INNER JOIN sys_user su ON su.id = sur.user_id " +
            "WHERE " +
            "su.id = ?1 AND sr.id = sur.role_id)"
             )
    List<SysRole> getRolesByUserId(Long userId);

    /**
     * 找到权限应的所有角色信息
     * @param permissionId
     * @return
     */
    @Query(nativeQuery = true, value = "SELECT\n" +
            "*\n" +
            "FROM\n" +
            "sys_role\n" +
            "WHERE\n" +
            "id IN (select srp.role_id from sys_role_permission srp where srp.permission_id=?1)")
    List<SysRole> listByPermissionId(Long permissionId);
}
